package com.freegeese.security.test.chapter2.permission;

import org.apache.shiro.authz.Permission;
import org.apache.shiro.util.StringUtils;

public class BitPermission implements Permission {
    protected static final String WILDCARD_TOKEN = "*";
    protected static final String PART_DIVIDER_TOKEN = "+";

    private String resourceId;
    private Integer permissionBit;
    private String instanceId;

    public BitPermission(String permissionString) {
        String[] parts = permissionString.split("\\" + PART_DIVIDER_TOKEN);
        // parse resource id
        if (parts.length > 1) {
            this.resourceId = parts[1];
        }
        if (!StringUtils.hasText(this.resourceId)) {
            this.resourceId = WILDCARD_TOKEN;
        }
        // parse permission bit
        if (parts.length > 2) {
            this.permissionBit = Integer.valueOf(parts[2]);
        }
        // parse instance id
        if (parts.length > 3) {
            this.instanceId = parts[3];
        }
        if (!StringUtils.hasText(this.instanceId)) {
            this.instanceId = WILDCARD_TOKEN;
        }
    }

    /**
     * 是否已经包含此Permission 依次比较 resourceId, permissionBit, instanceId
     *
     * @param p
     * @return
     */
    @Override
    public boolean implies(Permission p) {
        if (!BitPermission.class.isAssignableFrom(p.getClass())) {
            return false;
        }
        BitPermission other = (BitPermission) p;
        if (!(WILDCARD_TOKEN.equals(this.resourceId) || this.resourceId.equals(other.resourceId))) {
            return false;
        }
        if (!(this.permissionBit == 0 || (this.permissionBit & other.permissionBit) != 0)) {
            return false;
        }
        if (!(WILDCARD_TOKEN.equals(this.instanceId) || this.instanceId.equals(other.instanceId))) {
            return false;
        }
        return true;
    }
}
